/*
 * Copyright © 2024-2025 Wenze Wei
 *
 * This file is part of StadionOS.
 *
 * This Source Code Form is subject to the terms of the GNU General Public License, v. 2.0.
 * You can obtain a copy of the GPL at
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 */

#include "../include/malloc.h"

/**
 * @brief Reallocates memory.
 *
 * This function changes the size of the memory block pointed to by 'ptr' to 'new_size'.
 * If 'ptr' is NULL, it allocates a new block. If the new size is larger, it allocates a new block and copies the data.
 *
 * @param ptr A pointer to the memory block to be reallocated.
 * @param new_size The new size of the memory block.
 * @return void* A pointer to the reallocated memory, or NULL on error.
 */
void *Srealloc(void *ptr, size_t new_size) {  
    if (!ptr)
        return Smalloc(new_size);

    size_t old_size = ((TBlock *)ptr - 1)->size;
    if (new_size <= old_size)
        return ptr;

    void *new_ptr = Smalloc(new_size);
    if (!new_ptr)
        return NULL;

    Smemcpy(new_ptr, ptr, old_size);
    Sfree(ptr);

    return new_ptr;
}
